import { _decorator, Component, find, instantiate, Label, Node, Prefab, randomRange } from 'cc';
import { Sun } from '../Sun';
const { ccclass, property } = _decorator;

@ccclass('SunManager')
export class SunManager extends Component {
    private static _instance: SunManager = null;
    @property(Number)
    private sunPoint: number = 0;//总阳光值

    @property(Label)
    public sunPointLabel: Label = null;//阳光值显示

    @property(Number)
    produceTime: number = 0;//生产自然光时间间隔
    @property(Prefab)
    sunPrefab: Prefab = null;//阳光预制体
    isStartPruduceSun: boolean = false;//是否开始生产阳光
    /**
     * 获取实例
     */
    public static get Instance(): SunManager {
        return this._instance;
    }
    /**
     * 公共访问器 阳光值
     */
    public get SunPoint(): number {
        return this.sunPoint;
    }
    protected onLoad(): void {
        //确保全局只有一个实例
        if (SunManager._instance == null) {
            SunManager._instance = this;
        } else {
            console.log("SunManager is already exist");
            this.node.destroy();
        }
    }
    protected onDestroy(): void {
        if(SunManager.Instance==this){
            SunManager._instance=null;
            this.node.destroy();
        }
    }
    protected start(): void {
        // 更新太阳位置标签
        this.updateSunPointLabel();
        // this.startProduceSun();
    }
    protected update(dt: number): void {

        if (this.isStartPruduceSun) {
            // 安排定时任务，每隔 produceTime 时间执行 produceSun 方法
            this.schedule(this.produceSun, this.produceTime);
        }else{
            this.unschedule(this.produceSun);
        }
    }

    /**
     *  开始生产阳光开关
     */
    public startProduceSun() {
        this.isStartPruduceSun = true;
    }
    /**
     * 暂停生产阳光开关
     */
    pauseProduceSun() {
        this.isStartPruduceSun = false;
    }
    /**
     * 更新阳光值label显示
     */
    private updateSunPointLabel(): void {
        this.sunPointLabel.string = this.sunPoint.toString();
    }
    /**
     * 减少阳光值的方法
     * @param point 减少的阳光值
     */
    public subSun(point: number): void {
        // 从阳光值中减去给定的点数值
        this.sunPoint -= point;

        // 如果太阳点小于0，则将阳光值设置为0
        if (this.sunPoint < 0) {
            this.sunPoint = 0;
        }

        // 更新阳光值显示
        this.updateSunPointLabel();
    }
    public addSun(point: number): void {
        // 从阳光值中增加给定的点数值
        this.sunPoint += point;
        // 更新阳光值显示
        this.updateSunPointLabel();
    }
    /**
     * 生产自然阳光的方法
     */
    produceSun() {
        let sunNode = instantiate(this.sunPrefab);
        sunNode.parent = find("Canvas/ForeGround/SunGroup");
        let SunNodex = randomRange(-320, 460)
        sunNode.setPosition(SunNodex, 420);
        sunNode.getComponent(Sun).linearTo(SunNodex);
    }
}


